import { getNewCartGoods, mergeLocalCart, findCartList, insertCart, deleteCart, updateCart, checkAllCart } from '@/api/cart'

// 购物车状态
export default {
  namespaced: true,
  state: () => {
    return {
      list: []
    }
  },
  getters: {
    // 有效商品列表
    validList (state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },
    // 有效商品件数
    validTotal (state, getters) {
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品总金额
    validAmount (state, getters) {
      return getters.validList.reduce((p, c) => p + c.nowPrice * 100 * c.count, 0) / 100
    },
    // 无效商品列表
    invalidList (state) {
      return state.list.filter(item => !(item.stock > 0 && item.isEffective))
    },
    // 选中商品列表 (selected字段为true)
    selectedList (state, getters) {
      return getters.validList.filter(item => item.selected)
    },
    // 选中商品件数
    selectedTotal (state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 选中商品总金额
    selectedAmount (state, getters) {
      return getters.selectedList.reduce((p, c) => p + (c.nowPrice * 100 * c.count), 0) / 100
    },
    // 是否全选 (有效商品总数等于已选商品总数)
    isCheckAll (state, getters) {
      return getters.validList.length === getters.selectedList.length && getters.selectedList.length !== 0
    }
  },
  mutations: {
    // 单选功能
    singleCheck (state, { skuId, curCheck }) {
      const curItem = state.list.find(item => item.skuId === skuId)
      curItem.selected = curCheck
    },
    // 全选功能
    allCheck (state, curCheck) {
      state.list.forEach(item => {
        item.selected = curCheck
      })
    },
    // 加入购物车
    insertCart (state, goods) {
      const sameIndex = state.list.findIndex(item => item.skuId === goods.skuId)
      // 逻辑：有相同的给goods累加数量，删除相同skuId的商品
      if (sameIndex >= 0) {
        state.list[sameIndex].count = state.list[sameIndex].count + goods.count
      } else {
        state.list.unshift(goods)
      }
    },
    // 删除
    deleteCart (state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 数量修改
    changeCount (state, { skuId, count }) {
      const item = state.list.find(item => item.skuId === skuId)
      item.count = count
    },
    // 设置购物车列表
    setCartList (state, list) {
      state.list = list
    }
  },
  actions: {
    // 单选
    singleCheck (ctx, { good, selected }) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录 TODO
          updateCart({ ...good, selected }).then(() => {
            findCartList().then(data => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else {
          // 未登录 把商品信息加入本地vuex中
          ctx.commit('singleCheck', { skuId: good.skuId, selected })
          resolve()
        }
      })
    },
    // 全选
    allCheck (ctx, selected) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录 TODO
          const ids = ctx.getters.validList.map(item => item.skuId)
          checkAllCart({ selected, ids }).then(() => {
            findCartList().then(data => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else {
          // 未登录
          ctx.commit('allCheck', selected)
          resolve()
        }
      })
    },
    // 加入购物车
    insertCart (ctx, goods) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录 TODO
          insertCart(goods).then(() => {
            findCartList().then(data => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else {
          // 未登录 把商品信息加入本地vuex中
          ctx.commit('insertCart', goods)
          resolve()
        }
      })
    },
    // 删除购物车商品
    deleteCart (ctx, skuId) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录 TODO
          deleteCart([skuId]).then(() => {
            findCartList().then((data) => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else {
          // 本地
          ctx.commit('deleteCart', skuId)
          resolve()
        }
      })
    },
    // 修改数量
    changeCount (ctx, { good, count }) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录 TODO
          updateCart({ ...good, count }).then(() => {
            findCartList().then(data => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else {
          // 本地
          ctx.commit('changeCount', { skuId: good.skuId, count })
          resolve()
        }
      })
    },
    // 获取购物车列表
    findCartList (ctx) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录 TODO
          findCartList().then(data => {
            ctx.commit('setCartList', data.result)
            resolve()
          })
        } else {
          // 本地
          // Promise.all() 可以并列发送多个请求，等所有请求成功，调用then
          // Promise.race() 可以并列发送多个请求，等最快的请求成功，调用then
          // 传参事promise数组
          const promiseArr = ctx.state.list.map(item => {
            // 返回接口函数的调用
            return getNewCartGoods(item.skuId)
          })
          Promise.all(promiseArr).then(dataArr => {
            console.log(dataArr)
            dataArr.forEach((data, i) => {
              console.log('gengxin', data)
              ctx.commit('updateCart', { skuId: ctx.state.list[i].skuId, ...data.result })
            })
            resolve()
          }).catch(e => {
            reject(e)
          })
        }
      })
    },
    // 合并本地购物车
    async mergeLocalCart (ctx) {
      const cartList = ctx.state.list.map(({ skuId, selected, count }) => {
        return { skuId, selected, count }
      })
      await mergeLocalCart(cartList)
      // 合并成功将本地购物车删除
      ctx.commit('setCartList', [])
    }
  }
}
